import asyncio
import csv
import json
import hashlib
import os
import random
import sys
from llm_result_map_draw import deliver_money_linchart, draw_heat_map1, draw_heat_map2
from rider import Rider
import base64
import time
import pandas as pd
import ast
from test import getCapacity, transform_dict_to_3d_array, exp_to_params, extract_system_utility_data
from myModel import Model
from expDesign import getCapacityOne, getCapacityTwo, getCapacityThree, getCapacityFour

sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname("__file__"))))
from myModel import Model
from initmodel.initriders import init_riders
from agentDesign.L1.read_map import AStarPlanner, ReadMap
from agentDesign.graphSetting import nx_setting
import websockets
from mpi4py import MPI
from collections import Counter
from MeiTuan.generateOrders import data_list

read_map_all = ReadMap()
door_list_home = read_map_all.get_door("公司")
door_list_rest = read_map_all.get_door("饭店")
door_list_rider_live = read_map_all.get_door("洋房")


class MyServer:

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

        self.members_info = []
        self.days_info = 0
        self.interrupt_event = False
        self.resume_event = False
        self.model = None
        self.rider_num = 0  # 初始化奇手的个数
        self.time_step = 0  # 运行的步
        self.web_server = None
        self.choose_data = -1
        self.riders_info = []
        self.network_type = 'ER'  # 网络信息
        self.prob = 0  # 网络信息
        self.edge_BA = 3  # 网络信息
        self.neighbor_WS = 1  # 网络信息
        self.degree_RG = 1  # 网络信息
        self.probs_order = None  # 环境信息概率
        self.bf_order = 3  # 环境信息波峰
        self.edges = []
        self.llm_sex = []
        self.llm_work_status = []
        self.rider_learning_type = []
        self.class_type = []
        self.prob_mf = 0.5
        self.experiment_name = ''
        self.params_info = []  # 用来想前端展示
        self.params_info_initial = []  # 用来初始化模型
        self.run_step_time = 0  # 运行时间
        self.now_run_param = 0  # 当前运行的版本
        self.params_nx = []
        self.nx_exp_info = [] # 存放网络结构实验参数
        self.init_web_socket()

    def init_web_socket(self):

        self.web_server = websockets.serve(self.receive_info, self.ip, self.port, ping_timeout=60)
        asyncio.get_event_loop().run_until_complete(self.web_server)
        asyncio.get_event_loop().run_forever()

    async def reconnect_websocket(self):
        print("reconnect---------------------------")
        if self.web_server:
            self.web_server.serve.close()
            await self.web_server.serve.wait_closed()
        self.init_web_socket()

    async def receive_info(self, websocket):
        async for msg in websocket:
            try:
                data = self.parseJson(msg)
                await self.handle_events(data, websocket)
            except websockets.exceptions.ConnectionClosedError as e:
                print(f"Connection closed from {websocket.remote_address}: {e}")
                # await self.reconnect_websocket()

    async def init_model(self, data, websocket):
        #  启动模型
        global time_step, ONE_DAY, ONE_HOUR, ONE_MIN
        ONE_DAY = 360
        time_step = self.days_info * ONE_DAY
        ONE_HOUR = 30
        ONE_MIN = 2
        self.model = Model(MPI.COMM_WORLD, data, websocket)
        # await self.run_model_steps(time_step)

    async def run_model_steps(self, websocket):
        #  每个循环
        self.model.websocket = websocket
        self.model.step()
        self.time_step = self.model.runner_step
        await asyncio.sleep(0.01)

        # await self.model.close()

    async def stop_model_steps(self):
        await self.model.close()

    async def stop_model(self):
        # 中断模型的执行
        print("break start")
        self.interrupt_event = True
        self.resume_event = False

    async def restart_model(self):
        # 重新启动模型的执行
        self.interrupt_event = False
        self.resume_event = True

    async def handle_events(self, data, websocket):
        print(data, 'getData')
        if data["event"] == "day_y":  # 输入天数
            self.days_info = int(data["day"])
        elif data["event"] == "exp_nx":
            self.nx_exp_info = data['nx']
        # 初始界面-网络实验
        
        elif data["event"] == "exp_nx_params": # 存储生成的实验参数
            self.params_info_initial = []
            agent_ans = []
            for i, info in enumerate(self.class_type):
                agent_ans.append(info['learningType'])
            params_nx = exp_to_params(agent_ans, self.rider_num, [1 for _ in range(len(self.class_type) + 1)])
            for list_nx in self.nx_exp_info:
                tmp_params = params_nx[0] + [None,] + list_nx
                self.params_info_initial.append(tmp_params) #需要修改
            print(self.params_info_initial, "参数信息")
            last_four_elements = [sub_list[-5:] for sub_list in self.params_info_initial]
            await websocket.send(json.dumps({
                'uri': 'nx_exp_info',
                'data': last_four_elements
            }))
            
        elif data['event'] == 'move_data':
            print(data)
            start_row = data['start']
            end_row = data['stop']
            id_agent = data['id']
            nums = []
            with open('Storage/move.csv', 'r', encoding='utf-8') as file:
                reader = csv.reader(file)
                next(reader)  # 跳过标题行
                for i, row in enumerate(reader):
                    if start_row <= i <= end_row:
                        nums.append([int(row[id_agent * 2]), int(row[id_agent * 2 + 1])])
            # print(nums)
            await websocket.send(json.dumps({
                'uri': 'move',
                'data': nums
            }))

        elif data['event'] == "class_info":  # agent设计中打开学习信息设置按钮获得信息
            self.llm_sex = []
            self.llm_work_status = []
            self.class_type = []
            for info in data['data']:
                self.class_type.append(info)
            print(self.class_type)
        elif data['event'] == 'test_type':  # 对应的按钮是实验设计中预览按钮，进行传递信息，同时调同实验设计函数
            params = {'test1': [],
                      'test2': list(set(map(int, data['second']))),
                      'test3': list(set(map(int, data['third'])))}
            self.params_info = []
            for i in range(len(self.class_type)):
                tmp_ans = [0 for _ in range(len(self.class_type))]
                tmp_ans[i] += 1
                tmp = f"({':'.join(str(i) for i in tmp_ans)})"
                params['test1'].append(tmp)
            tmp = f"({':'.join(str(1) for _ in range(len(self.class_type)))})"
            params['test1'].append(tmp)
            ans = {}
            if data['type'] == "一次一因子设计":
                ans = getCapacityOne(1, params)
            elif data['type'] == 'NK因子设计':
                ans = getCapacityTwo(3, len(params['test1']), params)
            elif data['type'] == '网格设计':
                ans = getCapacityThree(params, 1)
            else:
                ans = getCapacityFour(params, 1)
            self.params_info = transform_dict_to_3d_array(ans)
            print('查看实验设计结果：', self.params_info)
            await websocket.send(json.dumps({'uri': 'exp_ans', 'data': self.params_info}))
        elif data["event"] == 'exp_send':
            print(data['agent_num'])
            self.rider_num = 0
            for i, info in enumerate(self.class_type):
                self.rider_num += data['agent_num'][i]
                self.rider_learning_type.extend([int(info['learningType'])] * data['agent_num'][i])
                self.llm_sex.extend([info['sex']] * data['agent_num'][i])
                self.llm_work_status.extend([info['workStatus']] * data['agent_num'][i])
            self.rider_num = data['agent_num']
            print('信息更新', self.rider_num, self.rider_learning_type, self.llm_sex, self.llm_work_status)
            # network: [this.activeName, this.prob, this.BA_add_edges, this.WS_init_neighbors, this.RG_init_degree]
            net_list = ['ER', 'BA', 'WS', 'RG', 'None']
            self.network_type = net_list[int(data['network'][0]) - 1]
            self.prob = int(data['network'][1])
            self.edge_BA = int(data['network'][2])
            self.neighbor_WS = int(data['network'][3])
            self.degree_RG = int(data['network'][4])
            print(self.network_type, self.prob, self.edge_BA, self.neighbor_WS, self.degree_RG)
        elif data['event'] == 'initial_set':
            self.rider_num = data['agent_num']
            self.run_step_time = data['step_num']
            net_list = ['ER', 'BA', 'WS', 'RG', 'None']
            self.network_type = net_list[int(data['network'][0]) - 1]
            self.prob = int(data['network'][1])
            self.edge_BA = int(data['network'][2])
            self.neighbor_WS = int(data['network'][3])
            self.degree_RG = int(data['network'][4])
            agent_ans = []
            for i, info in enumerate(self.class_type):
                agent_ans.append(info['learningType'])
            self.params_info_initial = exp_to_params(agent_ans, self.rider_num, [1 for _ in range(len(self.class_type) + 1)])
            print('test exp ans: ', self.params_info_initial)
        elif data['event'] == 'class_name':
            names = []
            for info in self.class_type:
                names.append(info['name'])
            await websocket.send(json.dumps({"uri": 'className',
                                             "data": names}))
        elif data['event'] == 'getAlgorithm':
            filename = "regulation/algorithm.json"
            with open(filename, 'r') as f:
                data = json.load(f)
            print(data)
            await websocket.send(json.dumps({'uri': 'getAlg', "message": "get message success", "data": data}))

        elif data['event'] == 'getAlgorithmByType':
            alType = list(data["type"])
            mapping = {'distribution': '1', 'dispatch algorithm': '2', 'reposition algorithm': '3'}

            filename = "regulation/algorithm.json"
            with open(filename, 'r') as f:
                data = json.load(f)
            print("1", data)
            algorithms = list()
            for d in data:
                if mapping[d['type']] in alType:
                    algorithms.append(d)

            await websocket.send(json.dumps({'uri': 'getAlg', "message": "get message success", "data": algorithms}))
        elif data['event'] == 'delAlgorithm':
            name = data['name']
            filename = "regulation/algorithm.json"
            with open(filename, 'r') as f:
                data = json.load(f)
            index = -1
            for i in range(len(data)):
                if data[i]['name'] == name:
                    index = i
            if index >= 0:
                del data[index]

            with open(filename, 'w') as f:
                json.dump(data, f)
            await websocket.send(json.dumps({'uri': 'delAlgorithm', 'data': data}))
        elif data['event'] == 'mf_info_confirm':
            self.prob_mf = data['prob']
        elif data["event"] == 'llm_info_confirm':  # agent设计学习方式中修改llm属性按钮
            self.llm_sex = [0 for _ in range(self.rider_num)]
            self.llm_work_status = [0 for _ in range(self.rider_num)]
            print('data', data['data'])
            for key, value in data['data'].items():
                print(value, 'info')
                self.llm_sex[value['id']] = int(value['sex'][0])
                self.llm_work_status[value['id']] = int(value['workAttribute'][0])
            print('info_sex_work', self.llm_sex, self.llm_work_status)
        elif data['event'] == 'levelOneInit':  # 因果分析第一层界面初始化
            learning_dict = {'模仿学习': 0,
                             'LLM': 1,
                             '强化学习': 2,
                             '规则式': 3,
                             '进化学习': 10}
            learning_dict2 = {'0': '模仿学习',
                              '1': 'LLM',
                              '2': '强化学习',
                              '3': '规则式',
                              '10': '进化学习'
                              }
            counter = [0] * len(learning_dict)

            sex_info = ['女', '男']
            work_info = {
                '1': '懒惰',
                '5': '普通',
                '10': '勤奋'
            }
            info_show = []
            for dict_rider in self.riders_info:
                counter[learning_dict[dict_rider['type']]] += 1
            for agent in self.model.context.agents(Rider.TYPE):
                info = '模仿学习概率: 0.5'
                if agent.learning_type == 1:
                    info = '性别：' + sex_info[agent.sex] + '; 工作态度：' + work_info[str(agent.diligent_level)]
                entry = {
                    'id': agent.id,
                    'type': learning_dict2[str(agent.learning_type)],
                    'info': info,
                    'money': agent.money
                }
                info_show.append(entry)
            info_three = ['区域数量： 5', '出发点分布：全选', '目的地分布：全选']
            info_order_prob = ''
            for key, info in self.model.order_prob.items():
                info_order_prob += '区域：' + str(key) + '，概率信息：' + str(info)
                info_order_prob += '|    |'
            info_three.append(info_order_prob)

            net_list = {
                'ER': ['随机网络', {'概率': self.prob}],
                'BA': ['无标度网络', {'BA_ADD_EDGES': self.edge_BA}],
                'WS': ['小世界网络', {'初始邻居': self.neighbor_WS}],
                'RG': ['规则网络', {'RG_init_degree': self.degree_RG}],
                'None': ['无网络', {}]
            }
            net_type = net_list[self.network_type][0]
            net_info = ''
            net_info_list = net_list[self.network_type][1]
            net_info += str(net_info_list)
            await websocket.send(json.dumps({"code": 200,
                                             "uri": "init_level_one",
                                             "rider_num": self.rider_num,
                                             'rider_MF_num': counter[0],
                                             'rider_LLM_num': counter[1],
                                             'rider_Nom_num': counter[2],
                                             'rider_RL_num': counter[3],
                                             'info_show': info_show,
                                             'info_three': info_three,
                                             'net_type': net_type,
                                             'net_info': net_info}))
        elif data['event'] == 'level_one_pic':  # 因果分析第一层图片
            image_folder = 'Storage/level_one'  # 图片文件夹路径
            for filename in os.listdir(image_folder):
                if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg'):
                    filepath = os.path.join(image_folder, filename)
                    with open(filepath, 'rb') as f:
                        image_data = f.read()
                        base64_data = base64.b64encode(image_data).decode('utf-8')
                        await websocket.send(json.dumps({
                            "uri": "get_pic",
                            "data": base64_data,
                        }))
                        time.sleep(0.001)
        elif data['event'] == 'levalTwoPic':  # 因果分析第2层图片
            image_folder = 'Storage/level_two'  # 图片文件夹路径
            for filename in os.listdir(image_folder):
                if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg'):
                    filepath = os.path.join(image_folder, filename)
                    with open(filepath, 'rb') as f:
                        image_data = f.read()
                        base64_data = base64.b64encode(image_data).decode('utf-8')
                        await websocket.send(json.dumps({
                            "uri": "get_pic",
                            "data": base64_data,
                        }))
                        time.sleep(0.001)
        elif data['event'] == 'pic_outlier':
            filepath = 'outiler_rep.png'
            with open(filepath, 'rb') as f:
                image_data = f.read()
                base_data = base64.b64encode(image_data).decode('utf-8')
                await websocket.send(json.dumps({
                    "uri": "pic_outlier",
                    "data": base_data,
                }))
        elif data['event'] == 'exp_img':
            # filepath = 'outiler.png'
            # filepath2 = 'metrics_heatmaps_with_repositon.png'
            # filepath3 = 'metrics_heatmaps_without_repositon.png'
            filepath = ['outiler_rep.png', 'metrics_heatmaps_with_repositon.png', 'metrics_heatmaps_without_repositon.png', 'outiler_withoutrep.png']
            base_data = []
            for path in filepath:
                with open(path, 'rb') as f:
                    image_data = f.read()
                    base_data.append(base64.b64encode(image_data).decode('utf-8'))
            await websocket.send(json.dumps({
                "uri": "pic_exp",
                "data": base_data
            })) 
            # with open(filepath, 'rb') as f:
            #     image_data = f.read()
            #     base_data = base64.b64encode(image_data).decode('utf-8')
            #     base_data2 = base64.b64encode(image_data2).decode('utf-8')
            #     base_data3 = base64.b64encode(image_data3).decode('utf-8')
            #     await websocket.send(json.dumps({
            #         "uri": "pic_exp",
            #         "data": base_data,
            #         'data2': 
            #     }))
        elif data['event'] == 'riders_num_3D':
            print("-------------" * 2)

            await websocket.send(json.dumps({"uri": "riders_num_3D",
                                             "num": self.rider_num + self.model.npc_num,
                                             "type": [],
                                             'edges': self.edges}))
        elif data["event"] == "rider_num":  # 初始设计中的旗手信息
            print('num', data)
            self.riders_info = []
            self.rider_num = data['data']
            for i in range(data['num1']):
                self.riders_info.append(
                    {'id': len(self.riders_info), 'money': 0, 'type': 'LLM', 'start': 1, 'stop': 200, 'career': 1})

            for i in range(data['num2']):
                self.riders_info.append(
                    {'id': len(self.riders_info), 'money': 0, 'type': '强化学习', 'start': 1, 'stop': 200, 'career': 1})

            for i in range(data['num3']):
                self.riders_info.append(
                    {'id': len(self.riders_info), 'money': 0, 'type': '模仿学习', 'start': 1, 'stop': 200, 'career': 1})

            for i in range(data['num4']):
                self.riders_info.append(
                    {'id': len(self.riders_info), 'money': 0, 'type': '规则式', 'start': 1, 'stop': 200, 'career': 1})
            print(self.rider_num)
        elif data['event'] == 'init_network':  # 初始化界面中的网络信息
            print('init_network', data)
            if data['type'] == 'first':
                self.network_type = 'ER'
                self.prob = data['prob']
            elif data['type'] == 'second':
                self.network_type = 'BA'
                self.edge_BA = data['edge']
            elif data['event'] == 'third':
                self.network_type = 'WS'
                self.neighbor_WS = data['edge']
            elif data['event'] == 'fifth':
                self.network_type = 'RG'
                self.degree_RG = data['edge']
            else:
                self.network_type = 'None'
        elif data['event'] == 'init_env':
            self.bf_order = data['bf']
            self.probs_order = data['prob']
            print('update info', self.bf_order, self.probs_order)
        elif data["event"] == "stop":
            await self.stop_model_steps()
        elif data["event"] == "restart":
            await self.restart_model()
        elif data["event"] == "info":  # 骑手的初始化信息
            await self.handle_riders(data, websocket)
        elif data["event"] == "start":  # 之前是move
            with open('memories/riders.json') as f:
                members = json.load(f)
            await self.init_model(members, websocket)
        elif data["event"] == "move":
            if self.model is None:
                with open('./memories/riders.json') as f:
                    example = json.load(f)
                self.rider_num = len(example['members'])
                await self.init_model(example, websocket)
            await self.run_model_steps(websocket)
            await websocket.send(json.dumps({"code": 200,
                                             "uri": "send_show_data",
                                             "data": self.model.show_data}))
        elif data["event"] == "init_agent":
            print('get_agent_data')

            await websocket.send(json.dumps({"code": 200,
                                             "uri": 'agent_info',
                                             "num": self.rider_num,
                                             'riders': self.riders_info
                                             }))
        elif data["event"] == 'update_agent':  # 详细Agent信息更新
            print('update_agent', data['data'])
            self.riders_info = data['data']
            print('棋手详细信息', self.riders_info)
        elif data['event'] == 'data_compare':
            ans1 = extract_system_utility_data('./info_log', 'utility.csv', 'system_utility')
            ans2 = extract_system_utility_data('./info_log', 'utility.csv', 'entropy')
            ans3 = extract_system_utility_data('./info_log', 'utility.csv', 'productivity')
            ans4 = extract_system_utility_data('./info_log', 'utility.csv', 'third')
            await websocket.send(json.dumps({
                "code": 200,
                'uri': 'data_compare',
                'sys_u': ans1,
                'ent': ans2,
                "pro": ans3,
                "agents_u": ans4
            }))
        elif data["event"] == "init_data":
            print("init data")
            all_items = os.listdir('./info_log')
            folder_nums = [int(name) for name in all_items if os.path.isdir(os.path.join('./info_log', name))]
            ans = 0
            if not int(data["data"]) == -1:
                ans = int(data["data"])
            # 读取一次数据
            columns_data = {name: [] for name in ['system_utility', 'entropy', 'productivity', 'third']}
            new_folder_path = os.path.join('./info_log', str(ans))
            csv_file_path = os.path.join(new_folder_path, 'utility.csv')
            with open(csv_file_path, "r", newline="") as file:
                reader = csv.DictReader(file)
                print(reader)
                for row in reader:
                    for name in columns_data:
                        columns_data[name].append(row[name])

            csv_move_path = os.path.join(new_folder_path, "agent_move.csv")
            data_move = []
            with open(csv_move_path, "r", newline="") as file:
                reader = csv.reader(file)
                for row_index, row in enumerate(reader):
                    for column_index, value in enumerate(row):
                        row = [row_index, int(column_index), int(value)]
                        data_move.append(row)

            data_money = []
            csv_money_path = os.path.join(new_folder_path, "agent_money.csv")
            with open(csv_money_path, "r", newline="") as file:
                reader = csv.reader(file)
                for row_index, row in enumerate(reader):
                    for column_index, value in enumerate(row):
                        data_money.append(float(value))

            # 读取棋手信息效能
            new_agent_u_path = os.path.join('./info_log', str(ans))
            csv_agent_path = os.path.join(new_agent_u_path, 'agent_utility.csv')
            agent_u_data = []
            agent_name = []
            with open(csv_agent_path, 'r', newline='') as csvfile:
                reader_agent = csv.DictReader(csvfile)
                for _ in range(len(reader_agent.fieldnames)):
                    agent_u_data.append([])
                for row in reader_agent:
                    for i in reader_agent.fieldnames:
                        agent_u_data[int(i)].append(float(row[i]))
                agent_name.extend(reader_agent.fieldnames)
            await websocket.send(json.dumps({"code": 200,
                                             "uri": "init_data",
                                             "data": [len(agent_name), 2, 3],
                                            #  'paramsInfo': self.params_info[ans],
                                            #  'runLen': self.run_step_time,
                                             "riderData": {
                                                 "value": agent_u_data,
                                                 "names": agent_name
                                             },
                                             "orderData": {
                                                 "value": [[10, 1, 0, 2],
                                                           [0, 1, 3, 2],
                                                           [5, 1, 0, 2],
                                                           [10, 1, 10, 2]],
                                                 "names": ['1', '2', '3', '4']
                                             },
                                             "utility": columns_data,
                                             "data_move": data_move,
                                             "data_money": data_money
                                             }))
        elif data['event'] == 'sys_begin':
            all_items = os.listdir('./info_log')
            folder_nums = [int(name) for name in all_items if os.path.isdir(os.path.join('./info_log', name))]
            await websocket.send(json.dumps({"code": 200,
                                             "uri": "data_chose",
                                             "data": folder_nums}))
        
        elif data['event'] == 'rule_class_info':
            nums = len(self.class_type)
            names = []
            for info in self.class_type:
                names.append(info['name'])
            await websocket.send(json.dumps({
                'uri': 'rule_class_info',
                'nums': nums,
                'names': names
            }))

        elif data["event"] == "init":
            with open('./memories/riders.json') as f:
                example = json.load(f)
            self.rider_num = len(example['members'])
            await self.init_model(example, websocket)
        # 传输信息
        elif data["event"] == "send_data":
            if self.model is None:
                print("请先选择实验场景并进行设置！！！！！！！！！！")
                await websocket.send(json.dumps({"code": 404,
                                                 "info": "请先选择实验场景并进行设置！！！！！！！！！！"}))
            else:
                await websocket.send(json.dumps({"code": 200, "uri": "send_data",
                                                 "data": self.model.show_data}))
                await self.run_model_steps(websocket)
                await asyncio.sleep(1)
        
        elif data["event"] == "orders_set":
            # event: 'orders_set', region_info: districtOrderRangesValues, time_info: regionsStartTimeValues, time_len: this.orderDayNum, BF_len: this.orderBF
            time_num = data['time_len']
            BF = data["BF_len"]
            prob_region = data['region_info']
            prob_time = data['time_info']
            ans = data_list(time_num, BF, prob_region, prob_time)
            print(ans)
            await websocket.send(json.dumps({"uri": "orders_list",
                                            "data": ans}))

        elif data['event'] == "graph_info":
            nodes_list, graph_list = nx_setting(data["params"], data['nx'])
            await websocket.send(json.dumps({
                "uri": "graph_list",
                "nodes": nodes_list,
                "lines": graph_list
            }))

        elif data["event"] == "get_data":
            if self.model is None:
                print("请先选择实验场景并进行设置！！！！！！！！！！")
                await websocket.send(json.dumps({"code": 404,
                                                 "info": "请先选择实验场景并进行设置！！！！！！！！！！"}))
            else:
                await websocket.send(json.dumps({"code": 200, "uri": "send_data",
                                                 "data": self.model.show_data}))
                # print(self.model.show_data)
                await asyncio.sleep(1)
        # 调控
        elif data['event'] == "regulation":
            print("regulation!!!!!", data['data'])
            if self.model is None:
                with open('memories/riders.json') as f:
                    members = json.load(f)
                await self.init_model(members, websocket)
            else:
                self.model.save_regulation_info(data['data']['regulation'], data['data']['detail'])
                # self.model.handle_regulation(data['data']['regulation'], data['data']['detail'])


        elif data['event'] == 'model_start':  # 网络图运行
            walk_time = [3 for _ in range(self.rider_num)]
            sleep_time = [200 for _ in range(self.rider_num)]
            learning_type = []
            start_params = self.params_info_initial[0]
            start_params[1] = websocket
            print('test_initial_info', start_params)
            self.now_run_param = 0
            self.model = Model(self.now_run_param, *start_params)
            print(self.params_info_initial, "参数信息")
            print('start', self.model.G.edges())
            for u, v in self.model.G.edges():
                edge = (u, v)
                self.edges.append(edge)
            await websocket.send(json.dumps({"uri": 'network_info',
                                             "rider_num": self.rider_num,
                                             'edges': self.edges}))
        elif data['event'] == 'run_model_step':  # 模型运行
            print('getInfo')
            if self.model.runner_step >= self.run_step_time:
                self.now_run_param += 1
                self.params_info_initial[self.now_run_param][1] = websocket
                self.model = Model(self.now_run_param, *self.params_info_initial[self.now_run_param])
            self.model.step()
            print('finish')
            edges = list(self.model.G.edges())

            await websocket.send(json.dumps({"code": 200,
                                             "uri": "send_show_data",
                                             "edges": edges,
                                             "data": self.model.show_data}))
        elif data['event'] == 'get_xlsx_data':
            print('需要发送文件')
            with open('Storage/实验报告模板.xlsx', 'rb') as f:
                xlsx_data = f.read()
            await websocket.send(xlsx_data)

        # llm结果分析
        elif data['event'] == 'draw_llm_result':
            print("draw_llm_result")
            draw_heat_map2.draw_heap_map()
            draw_heat_map1.draw_heap_map()
            deliver_money_linchart.draw_money_image()
            # 图片存放在/Storage/llm_result_image

        elif data['event'] == 'get_info_move':
            id_info = data['id']
            script_dir = os.path.dirname(os.path.abspath(__file__))
            move_path = os.path.join(script_dir, 'Storage/move_log')
            path_move = f"move.csv"
            filepath_move = os.path.join(move_path, path_move)
            df = pd.read_csv(filepath_move)
            column_data = df[str(id_info)]
            x = [ast.literal_eval(cell) for cell in column_data]
            await websocket.send(json.dumps({"code": 200,
                                             "uri": "get_info_move",
                                             "move": x}))
        elif data['event'] == 'report':
            with open('Storage/ans.png', 'rb') as f:
                image_data = f.read()
                base64_data = base64.b64encode(image_data).decode('utf-8')
                await websocket.send(json.dumps({
                    "uri": "report",
                    "data": base64_data,
                }))

    async def handle_riders(self, data, websocket):
        try:
            self.rider_num = data["riders_num"]
            self.members_info = data
            init_riders(data['riders_num'], data['riders_id'], data['riders_ration'], data['riders_money'],
                        data['riders_status'])
        except Exception as e:
            print(e)

    def parseJson(self, data):
        return json.loads(data)


if __name__ == "__main__":
    ip = 'localhost'
    port = 8766
    my_server = MyServer(ip, port)
